<?php
/**
 * 用户订单
 */

namespace app\api\controller\user;

use app\api\controller\Common;
use app\api\model\user\Membermodel;
use app\api\model\user\Ordermodel;
use think\Db;

class Order extends Common
{
    protected $data;
    public function initialize()
    {
        parent::initialize();
        $this->checkUserLogin(); // 验证登录
        $this->data = $this->request->except(['sign','accessKey','token']);
    }

    /**
     * 我的购买-订单列表
     */
    public function index(){
        $uid = $this->user['id'];
        $page = $this->data['page'] ? $this->data['page'] : 1;
        $order_type = $this->data['order_type'] ? $this->data['order_type'] : 1;
        $pageSize = $this->data['limit'] ? $this->data['limit'] : 20;
        $paginate = ['list_rows'=>$pageSize,'page'=>$page];
        $field = 'id,order_no,order_status,order_price,order_time,pay_time,send_time,cancel_time,refund_time,refund_time_end';
        switch($this->data['tab']){
            // 订单状态 1-待支付 2-已支付 3-已发货 4-已完成 5-已取消 6-已关闭 7-已退货 8-已退款
            // non-paymen待支付，non-dispatch待发货，dispatch待收货，finish已完成 cancel已取消 refund退款
            case 'non-payment': //未付款
                $list = db('order_info')->field($field)->where(['user_id'=>$uid, 'order_status'=>1, 'order_type' => $order_type])->order('id DESC')->paginate($paginate)->toArray();
                break;
            case 'non-dispatch': //待发货
                $list = db('order_info')->field($field)->where(['user_id'=>$uid, 'order_status'=>2, 'order_type' => $order_type])->order('pay_time DESC')->paginate($paginate)->toArray();
                break;
            case 'dispatch': //待收货
                $list = db('order_info')->field($field)->where(['user_id'=>$uid, 'order_status'=>3, 'order_type' => $order_type])->order('id DESC')->paginate($paginate)->toArray();
                break;
            case 'finish': //已完成
                $list = db('order_info')->field($field)->where(['user_id'=>$uid, 'order_status' =>4, 'order_type' => $order_type])->order('id DESC')->paginate($paginate)->toArray();
                break;
            case 'cancel': //已取消
                $list = db('order_info')->field($field)->where(['user_id'=>$uid, 'order_status' =>5, 'order_type' => $order_type])->order('id DESC')->paginate($paginate)->toArray();
                break;
            case 'refund': //退款
                $list = db('order_info')->field($field)->where(['user_id'=>$uid])->where('refund_status', '>', 0)->where(['order_type' => $order_type])->order('refund_time DESC')->paginate($paginate)->toArray();
                break;
            default:
                $list = db('order_info')->field($field)->where(['user_id'=>$uid, 'order_type' => $order_type])->order('id DESC')->paginate($paginate)->toArray();
                break;
        }

        if($list){
            foreach($list['data'] as $key=>$val){
                $field = 'goods_id,sku_id,goods_name,goods_pic,goods_num,sku_name,sku_price';
                $goods_list = db('order_goods')->field($field)->where('order_id', $val['id'])->select();
                $list['data'][$key]['goods'] = $goods_list;
            }
        }

        $account = db('users')->where('id', $uid)->value('account');
        $append = [
            'account' => $account,
        ];
        
        return $this->showSuccess('我的订单列表', $list, $append);
    }

    /**
     * 我的购买：课程订单列表
     */
    public function courseList()
    {
        $uid = $this->user['id'];
        $keyword = $this->data['keyword'];
        $page = $this->data['page'] ? $this->data['page'] : 1;
        $pageSize = $this->data['limit'] ? $this->data['limit'] : 20;
        $paginate = ['list_rows' => $pageSize, 'page' => $page];
        $field = 'a.id,a.order_no,a.order_status,a.order_price,a.order_time,a.pay_time,b.course_id,b.title,b.pic';
        $where = [];
        $where[] = ['a.user_id', '=', $uid];
        $where[] = ['a.order_status', '=', 2];
        $where[] = ['a.order_type', '=', 2];
        if($keyword){
            $where[] = ['b.title', 'like', '%'.$keyword.'%'];
        }
        $list = db('order_info')->alias('a')->field($field)
            ->leftJoin('order_course b', 'a.id=b.order_id')
            ->where($where)->order('a.pay_time DESC')->paginate($paginate)->toArray();

        return $this->showSuccess('我的课程列表', $list);
    }

    /**
     * 立即购买：结算商品列表
     */
    public function settleList()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];

        $goods_id = $this->data['goods_id'];
        $sku_id = $this->data['sku_id'];
        $goods_num = $this->data['goods_num'];

        if (!$goods_id ||!$sku_id  || !$goods_num) {
            $this->showError('参数错误', '403');
        }

        $detail = db('goods_info')->alias('a')->where('a.id', $goods_id)
            ->field('a.id,a.name goods_name,a.code,a.brand_id')
            ->find();
        if (!$detail) {
            $this->showError('商品不存在', '404');
        }

        $goods_sku = db('goods_info_sku')->field('id,desc,price,agent_price,stock')->where('id', $sku_id)->find();
        if ($goods_sku['stock'] - $goods_num < 0) {
            $this->showError('库存不足', '405');
        }
        $detail['sku_name'] = $goods_sku['desc'];
        $detail['stock'] = $goods_sku['stock'];
        $detail['goods_num'] = $goods_num;
        //加盟商价格判断
        $is_agent = $this->checkAgent($detail['brand_id']);
        if ($is_agent) {
            $detail['sku_price'] = $goods_sku['agent_price'];
        } else {
            $detail['sku_price'] = $goods_sku['price'];
        }

        // 商品图片
        $pic = db('goods_info_pic')->field('id,pic')->where('gid', $goods_id)->find();
        $detail['goods_pic'] = $pic['pic'];

        $account = db('users')->where('id', $user_id)->value('account');
        $append = [
            'transport' => '5.00',
            'account' => $account,
        ];
        return $this->showSuccess('立即购买提交订单前确认页面', $detail, $append);
    }

    /**
     * 立即购买：提交订单
     */
    public function createOrder(){
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $data = $this->data;
        $goods_id = $data['goods_id'];
        $sku_id = $data['sku_id'];
        $goods_num = $data['goods_num'];
        $address_id = $data['address_id'];

        $valid = $this->validate([
            'goods_id' => $goods_id,
            'sku_id' => $sku_id,
            'address_id' => $address_id,
            'goods_num' => $goods_num
        ],'app\api\validate\Orders');
        if(true !== $valid){
            $this->showError($valid, '403');
        }

        //商品详情
        $goodsInfo = db('goods_info')->alias('a')
            ->field('a.brand_id,b.title as brand_name,a.id goods_id,a.name goods_name,a.code,a.sale_price,a.original_price,a.status,a.desc,a.content,c.id sku_id,c.price,c.agent_price,c.desc sku_name,c.stock')
            ->leftJoin('goods_category b', 'b.id = a.brand_id')
            ->leftJoin('goods_info_sku c', 'a.id=c.gid')
            ->where('a.id', $goods_id)
            ->where('c.id', $sku_id)
            ->find();
        if (!$goodsInfo) {
            $this->showError('商品不存在', '402');
        }

        // 根据规格获取价格
        if ($goodsInfo['stock'] - $goods_num < 0) {
            $this->showError('库存不足', '405');
        }

        //加盟商价格判断
        $is_agent = $this->checkAgent($goodsInfo['brand_id']);
        if ($is_agent) {
            $goodsInfo['sku_price'] = $goodsInfo['agent_price'];
        } else {
            $goodsInfo['sku_price'] = $goodsInfo['price'];
        }
        unset($goodsInfo['agent_price'], $goodsInfo['price']);

        // 商品图片
        $pic = db('goods_info_pic')->field('id,pic')->where('gid', $goods_id)->find();
        $goods_pic = $pic['pic'];

        //创建订单
        $model = new Ordermodel();
        $order_no = date("Ymd").rand_string(8, 1);
        $addressInfo = Membermodel::getAddressInfo($address_id);
        $order_time = date('Y-m-d H:i:s', time());
        $order_price = $goodsInfo['sku_price'] * $goods_num;

        Db::startTrans();
        try {
            $order_info = [
                'order_no' => $order_no,
                'user_id' => $user_id,
                'address_id' => $address_id,
                'receive_address' => $addressInfo['address'],
                'receive_name' => $addressInfo['name'],
                'receive_phone' => $addressInfo['mobile'],
                'order_price' => $order_price,
                'order_status' => 1,
                'order_type' => 1,
                'order_time' => $order_time
            ];
            $insert_id = Db::table('order_info')->insertGetId($order_info);

            $order_goods = [
                'user_id'=> $user_id,
                'order_id'=> $insert_id,
                'goods_id' => $goods_id,
                'goods_num' => $goods_num,
                'goods_name' => $goodsInfo['goods_name'],
                'goods_pic' => $goods_pic,
                'goods_info' => json_encode($goodsInfo),
                'sku_id' => $goodsInfo['sku_id'],
                'sku_name' => $goodsInfo['sku_name'],
                'sku_price' => $goodsInfo['sku_price'],
                'create_time'=> $order_time
            ];
            Db::table('order_goods')->insert($order_goods);
            Db::table('goods_info_sku')->where('id', $sku_id)->setDec('stock', $goods_num);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->showError('创建订单失败！', 'GET_ERROR');
        }
        $this->showSuccess('创建成功', [
            'id'=> $insert_id,
            'order_no'=> $order_no,
            'order_price' => $order_price,
            'order_time' => $order_time,
            'order_type' => 1
        ]);
    }

    /**
     * 购物车：提交订单
     */
    public function createCartOrder()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $data = $this->data;
        $ids = $data['ids'];
        $address_id = $data['address_id'];
        if(!is_array($ids)){
            $ids = json_decode($ids, true);
        }

        if (!$ids || !is_array($ids) || !$address_id) {
            $this->showError('参数错误', '403');
        }

        foreach ($ids as $key => $cart_id) {
            $cartGoods = db('goods_cart')->alias('a')
                ->field('a.goods_id,a.goods_name,a.goods_num,a.sku_id,b.stock')
                ->leftJoin('goods_info_sku b', 'a.sku_id=b.id')
                ->where('a.user_id', $user_id)
                ->where('a.id', $cart_id)
                ->find();
            if (!$cartGoods) {
                continue;
            }
            if ($cartGoods['stock'] < $cartGoods['goods_num']) {
                $this->showError('商品'. $cartGoods['goods_name'].'库存不足，下单失败', 'NO_STOCK');
            }
        }

        //商品详情
        Db::startTrans();
        try {
            $order_price = 0;
            $order_time = date('Y-m-d H:i:s', time());
            $order_no = date("Ymd") . rand_string(8, 1);
            $addressInfo = Membermodel::getAddressInfo($address_id);
            $order_goods_insert_ids = [];
            foreach($ids as $key=>$cart_id){
                $cartGoods = db('goods_cart')->alias('a')
                    ->field('a.id,a.brand_id,b.title as brand_name,a.goods_id,a.goods_name,a.goods_pic,a.goods_num,a.sku_id,a.sku_name,c.price,c.agent_price,c.stock')
                    ->leftJoin('goods_category b', 'b.id = a.brand_id')
                    ->leftJoin('goods_info_sku c', 'a.sku_id=c.id')
                    ->where('a.user_id', $user_id)
                    ->where('a.id', $cart_id)
                    ->find();
                if($cartGoods['goods_num'] > $cartGoods['stock']){
                    // $this->showError('商品'. $goods['goods_name'].'库存不足，下单失败', 'NO_STOCK');
                }

                //加盟商价格判断
                $is_agent = $this->checkAgent($cartGoods['brand_id']);
                if ($is_agent) {
                    $cartGoods['sku_price'] = $cartGoods['agent_price'];
                } else {
                    $cartGoods['sku_price'] = $cartGoods['price'];
                }
                unset($goodsInfo['cartGoods'], $cartGoods['price']);

                $order_price += $cartGoods['sku_price'] * $cartGoods['goods_num'];

                $order_goods = [
                    'order_id' => 0,
                    'user_id' => $user_id,
                    'goods_id' => $cartGoods['goods_id'],
                    'goods_num' => $cartGoods['goods_num'],
                    'goods_name' => $cartGoods['goods_name'],
                    'goods_pic' => $cartGoods['goods_pic'],
                    'goods_info' => json_encode($cartGoods),
                    'sku_id' => $cartGoods['sku_id'],
                    'sku_name' => $cartGoods['sku_name'],
                    'sku_price' => $cartGoods['sku_price'],
                    'create_time' => $order_time
                ];
                $order_goods_insert_id = Db::table('order_goods')->insertGetId($order_goods);
                db('goods_cart')->where('id',$cartGoods['id'])->delete();
                $order_goods_insert_ids[] = $order_goods_insert_id;
                Db::table('goods_info_sku')->where('id', $cartGoods['sku_id'])->setDec('stock', $cartGoods['goods_num']);
            }
            $insert_id = Db::table('order_info')->insertGetId([
                    'order_no' => $order_no,
                    'user_id' => $user_id,
                    'address_id' => $address_id,
                    'receive_address' => $addressInfo['address'],
                    'receive_name' => $addressInfo['name'],
                    'receive_phone' => $addressInfo['mobile'],
                    'order_price' => $order_price,
                    'order_status' => 1,
                    'order_type' => 1,
                    'order_time' => $order_time,
            ]);
            Db::table('order_goods')->where('id', 'in', $order_goods_insert_ids)->update(['order_id' => $insert_id]);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
       
        $this->showSuccess('创建成功', [
            'id' => $insert_id,
            'order_no' => $order_no,
            'order_price' => $order_price,
            'order_time' => $order_time,
            'order_type' => 2
        ]);
    }

    /**
     * 立即购买：提交课程订单
     */
    public function createCourseOrder()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $data = $this->data;
        $course_id = $data['course_id'];

        if (!$course_id) {
            $this->showError('参数错误', '403');
        }

        //商品详情
        $goodsInfo = db('course')->where('id', $course_id)->find();
        if (!$goodsInfo) {
            $this->showError('课程不存在', '402');
        }

        //创建订单
        $order_no = date("Ymd") . rand_string(8, 1);
        $order_time = date('Y-m-d H:i:s', time());
        $order_price = $goodsInfo['price'];

        Db::startTrans();
        try {
            $order_info = [
                'order_no' => $order_no,
                'user_id' => $user_id,
                'order_price' => $order_price,
                'order_status' => 1,
                'order_type' => 2,
                'order_time' => $order_time
            ];
            $insert_id = Db::table('order_info')->insertGetId($order_info);

            $order_course = [
                'user_id' => $user_id,
                'order_id' => $insert_id,
                'course_id' => $course_id,
                'title' => $goodsInfo['title'],
                'pic' => $goodsInfo['pic'],
                'info' => json_encode($goodsInfo),
                'create_time' => $order_time
            ];
            Db::table('order_course')->insert($order_course);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->showError('创建订单失败！', 'GET_ERROR');
        }
        $this->showSuccess('创建成功', [
            'id' => $insert_id,
            'order_no' => $order_no,
            'order_price' => $order_price,
            'order_time' => $order_time,
            'order_type' => 2
        ]);
    }

    /**
     * 获取订单详情
     */
    public function detail(){
        $data = $this->data;
        $order_id = $data['id'];
        $uid = $this->user['id'];
        $model = new Ordermodel();
        $info = $model->orderDetail($order_id,$uid);
        if(!$info){
            $this->showError('订单不存在', 'GET_ERROR');
        }

        $account = db('users')->where('id', $uid)->value('account');
        $append = [
            'account' => $account,
        ];
        return $this->showSuccess('订单详情', $info, $append);
    }

    /**
     * 申请退款
     */
    public function applyRefund()
    {
        $data = $this->data;
        $order_id = $data['order_id'];
        $refund_desc = $data['refund_desc'];
        $res = db('order_info')->where('id', $order_id)->update(['refund_status' => 2, 'refund_desc'=> $refund_desc, 'refund_time'=>date('Y-m-d H:i:s')]);
        if (false !== $res) {
            $this->return = ['status' => 200, 'code' => 'SUCCESS', 'message' => '申请成功'];
        } else {
            $this->return = ['status' => 200, 'code' => 'GET_ERROR', 'message' => '失败'];
        }
        return $this->show($this->return);
    }

    /**
     * 取消订单
     */
    public function cancel(){
        $data = $this->data;
        $order_id = $data['order_id'];
        $model = new Ordermodel();
        $order = $model->getOrder($order_id, $this->user['id']);
        if(!$order){
            $this->showError('订单不存在', '401');
        }
        if ($order['order_status'] != 1) {
            $this->showError('此订单不能取消', '402');
        }
        $info = $model->cancelOrder($order_id);
        if(false !== $info){
            $orderGoods = db('order_goods')->where('order_id', $order_id)->select();
            foreach($orderGoods as $key=>$val){
                Db::table('goods_info_sku')->where('id', $val['sku_id'])->setInc('stock', $val['goods_num']);
            }
            $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'取消订单成功'];
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'取消失败'];
        }
        return $this->show($this->return);
    }

    /**
     * 删除（关闭）订单
     */
    public function close()
    {
        $data = $this->data;
        $order_id = $data['order_id'];
        $model = new Ordermodel();
        $order = $model->getOrder($order_id, $this->user['id']);
        if (!$order) {
            $this->showError('订单不存在', '401');
        }
        if (!($order['order_status'] == 4 || $order['order_status'] == 5)) {
            $this->showError('只有已取消/已完成的订单才能删除', '402');
        }
        $info = $model->closeOrder($order_id);
        if (false !== $info) {
            $this->return = ['status' => 200, 'code' => 'SUCCESS', 'message' => '删除订单成功'];
        } else {
            $this->return = ['status' => 200, 'code' => 'GET_ERROR', 'message' => '删除失败'];
        }
        return $this->show($this->return);
    }

    /**
     * 确认收货
     */
    public function verifyReceive()
    {
        $data = $this->data;
        $order_id = $data['order_id'];
        $model = new Ordermodel();
        $order = $model->getOrder($order_id, $this->user['id']);
        if (!$order) {
            $this->showError('订单不存在', '401');
        }
       
        $model->verifyReceive($order_id);
        $this->return = ['status' => 200, 'code' => 'SUCCESS', 'message' => '确认收货成功'];
       
        return $this->show($this->return);
    }

    /**
     * 现货出价 - 发货
     */
    public function sendOut(){
        $order_id = $this->data['id'];
        $express_id = $this->data['express_id'];
        $express_num = $this->data['express_num'];
        if(!$order_id || !$express_id || !$express_num){
            $this->showError('缺少参数');
        }
        $order = db('order_info')->where(['id'=>$order_id, 'order_status'=>2])->find();
        if(empty($order)){
            $this->showError('订单不存在，或未付款');
        }
        $spotOrder = db('spot_order_info')->where(['id'=>$order['spot_order_id'], 'order_status'=>42])->find();
        if(empty($spotOrder)){
            $this->showError('现货订单不存在');
        }
        //发货
        $res = db('order_info')->where('id',$order_id)->update([
            'express_id' => $express_id,
            'express_num' => $express_num,
            'order_status'=> 3,
            'send_time'=>date('Y-m-d H:i:s'),
        ]);
        if(!$res){
            $this->showError('购买订单发货失败');
        }
        $res = db('spot_order_info')->where('id',$spotOrder['id'])->update([
            'order_status'=> 43,
            'send_time'=>date('Y-m-d H:i:s'),
        ]);
        if(!$res){
            $this->showError('现货订单发货失败');
        }
        $this->showSuccess('OK');
    }

   
}